<template>
  <div class="products">
    <!-- 搜索表单 -->
    <el-card class="search-form">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="电子产品" value="electronics" />
            <el-option label="服装" value="clothing" />
            <el-option label="食品" value="food" />
            <el-option label="图书" value="books" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="上架" value="1" />
            <el-option label="下架" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增商品
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 商品表格 -->
    <el-card class="table-container">
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="商品名称" width="200" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)">
              {{ getCategoryName(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.stock > 10 ? 'success' : scope.row.stock > 0 ? 'warning' : 'danger'">
              {{ scope.row.stock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button type="info" size="small" @click="viewProduct(scope.row)">查看</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="rules"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="productForm.category" placeholder="请选择分类">
            <el-option label="电子产品" value="electronics" />
            <el-option label="服装" value="clothing" />
            <el-option label="食品" value="food" />
            <el-option label="图书" value="books" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="productForm.price" :min="0" :precision="2" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input-number v-model="productForm.stock" :min="0" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="productForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="productForm.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Products',
  setup() {
    const loading = ref(false)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const dialogTitle = ref('新增商品')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const multipleSelection = ref([])
    const productFormRef = ref()

    // 搜索表单
    const searchForm = reactive({
      name: '',
      category: '',
      status: ''
    })

    // 商品表单
    const productForm = reactive({
      id: null,
      name: '',
      category: '',
      price: 0,
      stock: 0,
      description: '',
      status: 1
    })

    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      category: [
        { required: true, message: '请选择商品分类', trigger: 'change' }
      ],
      price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' },
        { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
      ],
      stock: [
        { required: true, message: '请输入库存数量', trigger: 'blur' },
        { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'blur' }
      ],
      description: [
        { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
      ]
    }

    // 模拟数据
    const mockData = [
      {
        id: 1,
        name: 'iPhone 15 Pro',
        category: 'electronics',
        price: 7999.00,
        stock: 50,
        description: '最新款iPhone，配备A17 Pro芯片',
        status: 1,
        createTime: '2023-01-01 10:00:00'
      },
      {
        id: 2,
        name: 'MacBook Pro',
        category: 'electronics',
        price: 12999.00,
        stock: 20,
        description: '专业级笔记本电脑，适合开发和设计',
        status: 1,
        createTime: '2023-01-02 10:00:00'
      },
      {
        id: 3,
        name: '休闲T恤',
        category: 'clothing',
        price: 99.00,
        stock: 100,
        description: '舒适透气的纯棉T恤',
        status: 1,
        createTime: '2023-01-03 10:00:00'
      },
      {
        id: 4,
        name: '有机苹果',
        category: 'food',
        price: 15.00,
        stock: 0,
        description: '新鲜有机苹果，营养丰富',
        status: 0,
        createTime: '2023-01-04 10:00:00'
      },
      {
        id: 5,
        name: 'JavaScript高级程序设计',
        category: 'books',
        price: 89.00,
        stock: 30,
        description: '前端开发必读经典书籍',
        status: 1,
        createTime: '2023-01-05 10:00:00'
      },
      {
        id: 6,
        name: 'AirPods Pro',
        category: 'electronics',
        price: 1999.00,
        stock: 15,
        description: '主动降噪无线耳机',
        status: 1,
        createTime: '2023-01-06 10:00:00'
      },
      {
        id: 7,
        name: '牛仔裤',
        category: 'clothing',
        price: 299.00,
        stock: 5,
        description: '经典款牛仔裤，百搭时尚',
        status: 1,
        createTime: '2023-01-07 10:00:00'
      },
      {
        id: 8,
        name: '绿茶',
        category: 'food',
        price: 128.00,
        stock: 80,
        description: '优质绿茶，清香回甘',
        status: 1,
        createTime: '2023-01-08 10:00:00'
      }
    ]

    const tableData = ref([])

    // 获取分类名称
    const getCategoryName = (category) => {
      const categoryMap = {
        electronics: '电子产品',
        clothing: '服装',
        food: '食品',
        books: '图书'
      }
      return categoryMap[category] || category
    }

    // 获取分类标签类型
    const getCategoryType = (category) => {
      const typeMap = {
        electronics: 'primary',
        clothing: 'success',
        food: 'warning',
        books: 'info'
      }
      return typeMap[category] || 'default'
    }

    // 获取商品列表
    const getProductList = () => {
      loading.value = true
      // 模拟API请求
      setTimeout(() => {
        let filteredData = [...mockData]
        
        // 搜索过滤
        if (searchForm.name) {
          filteredData = filteredData.filter(item => 
            item.name.includes(searchForm.name)
          )
        }
        if (searchForm.category) {
          filteredData = filteredData.filter(item => 
            item.category === searchForm.category
          )
        }
        if (searchForm.status !== '') {
          filteredData = filteredData.filter(item => 
            item.status === parseInt(searchForm.status)
          )
        }

        total.value = filteredData.length
        
        // 分页
        const start = (currentPage.value - 1) * pageSize.value
        const end = start + pageSize.value
        tableData.value = filteredData.slice(start, end)
        
        loading.value = false
      }, 500)
    }

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      getProductList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        name: '',
        category: '',
        status: ''
      })
      handleSearch()
    }

    // 新增商品
    const handleAdd = () => {
      isEdit.value = false
      dialogTitle.value = '新增商品'
      dialogVisible.value = true
    }

    // 查看商品详情
     const viewProduct = (row) => {
       router.push({
         path: '/detail',
         query: {
           type: 'product',
           id: row.id,
           action: 'view'
         }
       })
     }

    // 编辑商品
    const handleEdit = (row) => {
      isEdit.value = true
      dialogTitle.value = '编辑商品'
      Object.assign(productForm, { ...row })
      dialogVisible.value = true
    }

    // 删除商品
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除商品 "${row.name}" 吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 模拟删除操作
        const index = mockData.findIndex(item => item.id === row.id)
        if (index > -1) {
          mockData.splice(index, 1)
          getProductList()
          ElMessage.success('删除成功')
        }
      })
    }

    // 批量删除
    const handleBatchDelete = () => {
      ElMessageBox.confirm(
        `确定要删除选中的 ${multipleSelection.value.length} 个商品吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 模拟批量删除操作
        multipleSelection.value.forEach(item => {
          const index = mockData.findIndex(data => data.id === item.id)
          if (index > -1) {
            mockData.splice(index, 1)
          }
        })
        getProductList()
        ElMessage.success('批量删除成功')
      })
    }

    // 选择改变
    const handleSelectionChange = (val) => {
      multipleSelection.value = val
    }

    // 分页大小改变
    const handleSizeChange = (val) => {
      pageSize.value = val
      getProductList()
    }

    // 当前页改变
    const handleCurrentChange = (val) => {
      currentPage.value = val
      getProductList()
    }

    // 提交表单
    const submitForm = () => {
      productFormRef.value.validate((valid) => {
        if (valid) {
          if (isEdit.value) {
            // 编辑商品
            const index = mockData.findIndex(item => item.id === productForm.id)
            if (index > -1) {
              Object.assign(mockData[index], { ...productForm })
              ElMessage.success('编辑成功')
            }
          } else {
            // 新增商品
            const newProduct = {
              ...productForm,
              id: Date.now(),
              createTime: new Date().toLocaleString()
            }
            mockData.unshift(newProduct)
            ElMessage.success('新增成功')
          }
          dialogVisible.value = false
          getProductList()
        }
      })
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(productForm, {
        id: null,
        name: '',
        category: '',
        price: 0,
        stock: 0,
        description: '',
        status: 1
      })
      if (productFormRef.value) {
        productFormRef.value.clearValidate()
      }
    }

    onMounted(() => {
      getProductList()
    })

    return {
      loading,
      dialogVisible,
      isEdit,
      dialogTitle,
      currentPage,
      pageSize,
      total,
      multipleSelection,
      productFormRef,
      searchForm,
      productForm,
      rules,
      tableData,
      getCategoryName,
      getCategoryType,
      handleSearch,
      resetSearch,
      handleAdd,
      viewProduct,
      handleEdit,
      handleDelete,
      handleBatchDelete,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.products {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.operation-buttons {
  margin-bottom: 20px;
}

.table-container {
  background: white;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-form .el-form-item {
  margin-bottom: 20px;
}
</style>